package com.fks.fks_service.controller;

import com.fks.fks_service.base.JsonResult;
import com.fks.fks_service.base.ResultCode;
import com.fks.fks_service.mapper.*;
import com.fks.fks_service.pojo.*;
import com.fks.fks_service.utils.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Transactional//开启事务回滚
@Api(tags = "管理员模块")
public class AdminController {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    UserDBMapper userDBMapper;
    @Autowired
    ShopOrderMapper shopOrderMapper;
    @Autowired
    PasswordEncoder passwordEncoder;


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "userId",value = "用户id",required = true,paramType = "param"),
            @ApiImplicitParam(name = "IdentityInformationVerification",value = "实名信息审核，0未申请，1审核中，2审核成功，3审核失败",required = true,paramType = "param"),
    })
    @ApiOperation(value = "审核实名认证", notes = "审核实名认证")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/realNameVerification")
    public JsonResult realNameVerification(HttpServletRequest request){
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id和账号类型
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        //权限判断
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"admin".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        int adminId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        Admin admin = adminMapper.getById(adminId);

        String userId = request.getParameter("userId");
        String IdentityInformationVerification = request.getParameter("IdentityInformationVerification");
        if (userId==null||"".equals(userId)){
            return JsonResult.error(2000,"缺少用户id");
        }
        if (IdentityInformationVerification==null||"".equals(IdentityInformationVerification)){
            return JsonResult.error(2000,"请输入身份证");
        }

        userDBMapper.realNameVerification(userId,IdentityInformationVerification);

        return JsonResult.success("操作申请成功");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,paramType = "param"),
            @ApiImplicitParam(name = "pageSize",value = "每页数量",required = true,paramType = "param"),
    })
    @ApiOperation(value = "获取实名认证审核列表", notes = "获取实名认证审核列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/getRealNameAuthenticationList")
    public JsonResult getRealNameAuthenticationList(HttpServletRequest request){
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id和账号类型
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        //权限判断
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"admin".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        int adminId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        Admin admin = adminMapper.getById(adminId);

        if (request.getParameter("page")==null||"".equals(request.getParameter("page"))){
            return JsonResult.error(2000,"缺少参数");
        }
        if (request.getParameter("pageSize")==null||"".equals(request.getParameter("pageSize"))){
            return JsonResult.error(2000,"缺少参数");
        }
        int page = Integer.parseInt(request.getParameter("page"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        List<UserDB> realNameAuthenticationList = userDBMapper.getRealNameAuthenticationList(page, pageSize);

        return JsonResult.success("获取实名认证审核列表成功").data(realNameAuthenticationList);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,paramType = "param"),
            @ApiImplicitParam(name = "pageSize",value = "每页数量",required = true,paramType = "param"),
    })
    @ApiOperation(value = "获取用户详情列表", notes = "获取用户详情列表")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/getUserDetailsList")
    public JsonResult getUserDetailsList(HttpServletRequest request){
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id和账号类型
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        //权限判断
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"admin".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        int adminId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        Admin admin = adminMapper.getById(adminId);

        if (request.getParameter("page")==null||"".equals(request.getParameter("page"))){
            return JsonResult.error(2000,"缺少参数");
        }
        if (request.getParameter("pageSize")==null||"".equals(request.getParameter("pageSize"))){
            return JsonResult.error(2000,"缺少参数");
        }
        int page = Integer.parseInt(request.getParameter("page"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        List<UserDB> list = userDBMapper.getUserDetailsList((page-1)*pageSize, pageSize);
        int count = userDBMapper.getUserDetailsCount();
        List<UserDB> userDetailsList = new ArrayList<>();
        for (UserDB userDB : list) {
            //获取用户直推人数
            int directUserNumber = userDBMapper.getUserDirectUserNumber(userDB.getId());
            userDB.setDirectUserNumber(String.valueOf(directUserNumber));
            //获取用户间推人数
            int indirectUserNumber = userDBMapper.getUserIndirectUserNumber(","+userDB.getId()+",");
            if (indirectUserNumber>0){
                userDB.setIndirectUserNumber(String.valueOf(indirectUserNumber));
            }else {
                userDB.setIndirectUserNumber("0");
            }
            //获取团队设备数
            int teamDeviceNumber = userDBMapper.getTeamDeviceNumber(","+userDB.getId()+",");
            if (teamDeviceNumber>0){
                userDB.setTeamDeviceNumber(String.valueOf(teamDeviceNumber));
            }else {
                userDB.setTeamDeviceNumber("0");
            }
            userDetailsList.add(userDB);
        }
        return JsonResult.success("获取用户详情列表成功").data(userDetailsList).put("count",count);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
    })
    @ApiOperation(value = "获取管理员详情", notes = "获取管理员详情")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功")
    })
    @PostMapping("/api/getAdminInfo")
    public JsonResult getAdminInfo(HttpServletRequest request){
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id和账号类型
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        //权限判断
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"admin".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }
        int adminId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        Admin admin = adminMapper.getById(adminId);
        admin.setToken(token);
        //隐私信息加密
        admin.setPassword("****");

        return JsonResult.success("获取管理员详情成功").data(admin);
    }
    

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "phone",value = "电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,paramType = "param"),
            @ApiImplicitParam(name = "userUniqueIdentification",value = "邀请码",required = false,paramType = "param"),
    })
    @ApiOperation(value = "手机号进行用户注册", notes = "手机号进行用户注册")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = UserDB.class)
    })
    @PostMapping("/api/registerPhone")
    public JsonResult registerPhone(HttpServletRequest request) {
        //校验参数
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id和账号类型
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        //权限判断
        String accountType = String.valueOf(tokenClaims.get("accountType"));
        if (!"admin".equals(accountType)){
            return JsonResult.error(ResultCode.param_is_null,"权限不足");
        }

        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        String userUniqueIdentification = request.getParameter("userUniqueIdentification");
        System.out.println("phone:"+phone);
        //检验手机号
        if (!WPhoneUtils.isChinaPhone(phone)) {
            return JsonResult.error(ResultCode.phone_format_error,"请填写正确的手机号");
        }
        if (phone==null||"".equals(phone)) {
            return JsonResult.error(ResultCode.phone_format_error,"手机号不能为空");
        }
        String payPassword="123456";

        //用户校验
        UserDB registerUserDB = userDBMapper.selectUserByUsername(phone);
        if (registerUserDB != null) {
            return JsonResult.error(ResultCode.phone_format_error,"用户已存在");
        }
        //判断是否有密码
        if(password==null||"".equals(password)){
            return JsonResult.error(ResultCode.phone_format_error,"密码不能为空");
        }

        String[] split = phone.split("");


        //设置新用户信息
        registerUserDB = new UserDB();
        registerUserDB.setUserName("科创互联"+split[9]+split[10]);
        registerUserDB.setPhone(phone);
        registerUserDB.setNickName("科创互联"+split[9]+split[10]);
        registerUserDB.setPassword(passwordEncoder.encode(password));
        registerUserDB.setPayPassword(payPassword);
        registerUserDB.setCreateTime(DateUtils.getNowTime());
        registerUserDB.setAvatar("http://www.longshijieapp.com/kchlimages/kchl.png");
        //生成用户唯一标识
        String uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
        UserDB userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        while (userDB != null) {
            uniqueIdentification = RandomStringUtils.randomAlphanumeric(8);
            userDB = userDBMapper.getUserByUniqueIdentification(uniqueIdentification);
        }

        registerUserDB.setUserUniqueIdentification(uniqueIdentification);

        if (userUniqueIdentification!=null) {
            //邀请码设置
            UserDB user = userDBMapper.selectUserByUserUniqueIdentification(userUniqueIdentification);
            if (user==null){
                return JsonResult.error(ResultCode.phone_format_error,"推荐码错误");
            }
            registerUserDB.setDirectUid(String.valueOf(user.getId()));
            //设置间接推荐
            String indirectUid="";
            if (user.getIndirectUid()!=null&&!"".equals(user.getIndirectUid())){
                indirectUid= user.getIndirectUid()+user.getId()+",";
            }else {
                indirectUid= ","+user.getId()+",";
            }
            if (indirectUid!=""){
                registerUserDB.setIndirectUid(indirectUid);
            }
        }

        //用户注册
        userDBMapper.insertUserDB(registerUserDB);

        registerUserDB = userDBMapper.selectUserByUsername(phone);
        int userId = registerUserDB.getId();

        //用户校验
        UserDB user = userDBMapper.selectUserByUsername(phone);

        //自动注册系列软件
        //获取直推用户电话
        UserDB directUser = userDBMapper.getUserById(Integer.parseInt(user.getDirectUid()));
        if (directUser==null){
            AutomaticLogonUtil.automaticLogon(phone,"0",password,user.getPayPassword());
        }else {
            AutomaticLogonUtil.automaticLogon(phone,directUser.getPhone(),password,user.getPayPassword());
        }

        return JsonResult.success("注册成功");
    }



}
